#include "beidoupower.h"
#include "framewindow.h"

#include <QDateTime>
#include <QSerialPortInfo>
#include <QtDebug>


BeiDouPower::BeiDouPower()
{

}

BeiDouPower::BeiDouPower(FrameWindow *frameWindow)
{
    this->parent = frameWindow;

    connect(this, &BeiDouPower::single_finish,
            parent,&FrameWindow::slot_finished_beidou_COM);
}


QString BeiDouPower::FindMCU_COM(){

    QString com_name;
    foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
    {


        if(this->parent->beidou_is_stop){
           break;
        }

        if(!info.description().isEmpty()){

            // 设置串口号
            QSerialPort * serialPort = new QSerialPort();
            serialPort->setPortName(info.portName());


            /*
            if(serialPort->isOpen())//如果串口已经打开了 先给他关闭了
            {
                serialPort->clear();
                serialPort->close();
            }
            */

            serialPort->close();
            if(!serialPort->open(QIODevice::ReadWrite))
            {
                qDebug()<<info.portName()<<" 打开失败!";
                delete serialPort;
                serialPort = nullptr;
                continue;
            }

            serialPort->setBaudRate(115200);
            serialPort->setDataBits(QSerialPort::Data8);
            serialPort->setParity(QSerialPort::NoParity);
            serialPort->setStopBits(QSerialPort::OneStop);
            serialPort->setFlowControl(QSerialPort::NoFlowControl);

            QString sendHandshake="68020268CBB17C16";
            QString ResponseHandshake ="68020268ABB15C16";

            qDebug() << QDateTime::currentDateTime().toString("[yyyy-MM-dd hh:mm:ss zzz]") <<
                        "Sent Handshake command:"<<info.portName()<<sendHandshake;

            serialPort->write(QByteArray::fromHex(sendHandshake.toUtf8()));


            if (serialPort->waitForBytesWritten(2000)) {

                if (serialPort->waitForReadyRead(2000)) {

                    QByteArray responseData = serialPort->readAll();
                    while (serialPort->waitForReadyRead(1000))
                    {
                        responseData += serialPort->readAll();
                    }

                    QString revHandshake = responseData.toHex().toUpper();

                    if( revHandshake == ResponseHandshake ){

                        qDebug() << QDateTime::currentDateTime().toString("[yyyy-MM-dd hh:mm:ss zzz]") <<
                                    "Received Handshake response: "<<revHandshake;
                        qDebug() << "MCU COM is :"<< info.portName();
                        com_name = info.portName();
                    }
                }
            }


            serialPort->close();
            delete serialPort;
            serialPort = nullptr;

            if(!com_name.isEmpty()){
                break;
            }

        }
    }

    return  com_name;
}


void BeiDouPower::run()
{
    QString McuComName = FindMCU_COM();
    QString BdComName;

    if( McuComName.isEmpty() ){
        qDebug() << "MCU  serial port is  EMPTY!";
        return;
    }


    /*
     * Fist Time to list Ports
     */
    QList<QSerialPortInfo> com_list_last= QSerialPortInfo::availablePorts();


    // 设置串口号
    QSerialPort * serialPort = new QSerialPort();
    serialPort->setPortName(McuComName);
    if(!serialPort->open(QIODevice::ReadWrite))
    {
        delete serialPort;
        serialPort = nullptr;
        return;

    }

    serialPort->setBaudRate(115200);
    serialPort->setDataBits(QSerialPort::Data8);
    serialPort->setParity(QSerialPort::NoParity);
    serialPort->setStopBits(QSerialPort::OneStop);
    serialPort->setFlowControl(QSerialPort::NoFlowControl);

    QString openPower="68020268CAA16B16";
    QString ResponseOpenPower ="68020268AAA14B16";
    qDebug() << "Sent Power on command to Beidou COM:"<<McuComName<<openPower;


    serialPort->write(QByteArray::fromHex(openPower.toUtf8()));
    bool isOn = false;
    if (serialPort->waitForBytesWritten()) {

        if (serialPort->waitForReadyRead()) {
            msleep(2000);
            QByteArray revBuffer= serialPort->readAll();
            QString revString = revBuffer.toHex().toUpper();

            if(revString==ResponseOpenPower){
                qDebug() <<"Power On! Received: "<<revString;
                isOn = true;
            }
        }
    }

     // Close MCU　Port
    serialPort->clear();
    serialPort->close();


    if(isOn){

        msleep(20000);// Wait for the BeiDou port on Windows to appear.
        /*
         * Second Time to list Ports
         */
        QList<QSerialPortInfo> com_list_update = QSerialPortInfo::availablePorts();
        foreach (const QSerialPortInfo &COM_update, com_list_update)
        {
            bool isSame = false;

            foreach (const QSerialPortInfo &COM_last, com_list_last)
            {
                if(COM_last.portName()==COM_update.portName()){
                    isSame= true;
                    break;
                }
            }

            if(!isSame){// 没有找到，说明是第二次新增出来的串口
                BdComName = COM_update.portName();
                break;

            }
        }

    }

    qDebug() <<" Beidou Port Name："<<BdComName;
    if(!BdComName.isEmpty()){
        parent->name_BD_COM = BdComName;
    }

    // 如果没有识别的北斗串口，则使用上次的串口


    // 通知北斗常规接收线程启动
    emit single_finish(parent->name_BD_COM);







}
